import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

//包子资源类
class Bun {
  String pier;
  String xianer;
  boolean hasBun = false; // 有没有面包
}

// 吃货线程类：
class Foodie extends Thread {
  private final Bun bun;

  public Foodie(final String name, final Bun bun) {
    super(name);
    this.bun = bun;
  }

  @Override
  public void run() {
    while (true) {
      synchronized (bun) {
        if (bun.hasBun == false) {
          try { // 没有包子等待
            bun.wait();
          } catch (final InterruptedException e) {
            e.printStackTrace();
          }
        }
        try {
          System.out.println(this.getName() + ":吃货正在吃...");
          sleep(3000);
    	  System.out.println("----------- 吃完了 -----------\n");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        bun.hasBun = false;
        bun.notify();
      }
    }
  }
}

class BunShop extends Thread {
  private final Bun bun; // 创建一个包子变量

  public BunShop(final String name, final Bun bun) {
    super(name);
    this.bun = bun;
  }

  @Override
  public void run() {
    while (true) {
      synchronized (bun) {
        if (bun.hasBun == true) {
          try { // 有包子不用再做
            Thread.sleep(1000);
            System.out.println("还有面包,面包师傅休息(进入wait())");
          } catch (final InterruptedException e) {
            e.printStackTrace();
          }
        }

        // 没有的时候，开始做包子
        System.out.println("++++++++++ 包子铺开始做包子 ++++++++++");
        try {
          sleep(new Random().nextInt(5000) + 2000);
        } catch (final InterruptedException e) {
          e.printStackTrace();
        }

        final ArrayList<Object> list = new ArrayList<>();
        list.addAll(Arrays.asList("🐀", "🐂", "🐅", "🐇", "🐉", "🐍", "🐎", "🐏", "🐒", "🐓", "🐕", "🐖"));
        bun.pier = (String) list.get(new Random().nextInt(12));
        bun.xianer = "肉包子馅";
        bun.hasBun = true;
        System.out.println(this.getName() + ":" + bun.pier + bun.xianer + "包子做好了");
try {
  bun.wait();
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
        bun.notify(); // 唤醒等待线程
  
      }
    }
  }
}

// 测试类
public class Demo {
  public static void main(final String[] args) {
    final Bun bun = new Bun();
    final BunShop bunshop = new BunShop("包子铺类线程", bun);
    final Foodie foodie = new Foodie("吃货类线程", bun);
    bunshop.start();
    foodie.start();
  }
}